//
//  CKCircleView2.m
//  CKCircleWidget
//
//  Created by Aileen Nielsen on 11/18/15.
//  Copyright © 2015 SunnysideProductions. All rights reserved.
//

#define   DEGREES_TO_RADIANS(degrees)  ((M_PI * degrees)/ 180)

#import "CKCircleView.h"
#import <math.h>
#import <QuartzCore/QuartzCore.h>


@interface CKCircleView () <UIGestureRecognizerDelegate>
@property CGPoint trueCenter;


@property double angle;
@property UIView *circle;

@end

@implementation CKCircleView



# pragma mark view appearance setup

- (id) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        // overall view settings
        self.userInteractionEnabled = YES;
        self.clipsToBounds = YES;
        
        // setting default values
        self.minNum = 0;
        self.maxNum = 20;
        self.currentNum = self.minNum;
        self.units = @"";
        
        // determine true center of view for calculating angle and setting up arcs
        CGFloat width = frame.size.width;
        CGFloat height = frame.size.height;
        self.trueCenter = CGPointMake(width/2, height/2);
        
        // radii settings
        self.dialRadius = 10;
        self.arcRadius = 50;
        self.outerRadius = MIN(width, height)/2;
        self.arcThickness = 5.0;
        
        self.circle = [[UIView alloc] initWithFrame:CGRectMake((width - self.dialRadius*2)/2, height*.25, self.dialRadius*2, self.dialRadius*2)];
        self.circle.userInteractionEnabled = YES;
        [self addSubview: self.circle];
        

        
        // pan gesture detects circle dragging
        UIPanGestureRecognizer *pv = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
        [self addGestureRecognizer:pv];
        
        self.arcColor = [UIColor whiteColor];
        self.backColor = [UIColor yellowColor];
        self.dialColor = [UIColor blueColor];
        self.labelColor = [UIColor blackColor];
        

        
    }
    
    return self;
}

- (void) drawRect:(CGRect)rect {
    UIColor *color = self.arcColor;
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 3);
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextSetStrokeColorWithColor(context, color.CGColor);
    UIBezierPath *path = [self createArcPathWithAngle:self.angle atPoint:self.trueCenter withRadius:self.arcRadius];
    path.lineWidth = self.arcThickness;
    if(self.angle >=0 && self.currentNum>0)[path stroke];
    
}

- (void) willMoveToSuperview:(UIView *)newSuperview{
    [super willMoveToSuperview:newSuperview];
    
    
    self.arcRadius = MIN(self.arcRadius, self.outerRadius - self.dialRadius);
    
    // background circle
    self.layer.cornerRadius = self.outerRadius;
    self.backgroundColor = self.backColor;
    
    // dial
    self.circle.frame =  CGRectMake(50, 195, self.dialRadius*2, self.dialRadius*2);
    self.circle.backgroundColor = self.dialColor;
    
    //为透明度设置渐变效果
    UIColor *colorOne = [UIColor colorWithRed:(61/255.0)  green:(230/255.0)  blue:(114/255.0)  alpha:0.7];
    UIColor *colorTwo = [UIColor colorWithRed:(41/255.0)  green:(189/255.0)  blue:(237/255.0)  alpha:0.7];
    
    CAGradientLayer *gradientLayer =  [CAGradientLayer layer];
    gradientLayer.frame = self.circle.bounds;
    //设置颜色
    [gradientLayer setColors:[NSArray arrayWithObjects:(id)[colorOne CGColor],(id)[colorTwo CGColor], nil]];
    //每种颜色最亮的位置
    //    [gradientLayer setLocations:@[@.5,@.5]];
    //渐变的方向StartPoint－>EndPoint
    [gradientLayer setStartPoint:CGPointMake(0, 0)];
    [gradientLayer setEndPoint:CGPointMake(1, 1)];
    [self.circle.layer addSublayer:gradientLayer];
    
     [self.circle setShearRound:self.circle.width/2 masksToBounds:YES borderWidth:3 borderColor:[UIColor whiteColor]];

    
}


# pragma mark move circle in response to pan gesture

- (void) moveCircleToAngle: (double)angle{
    self.angle = angle;
    [self setNeedsDisplay];
    
    CGFloat width = self.frame.size.width;
    CGFloat height = self.frame.size.height;
    CGPoint newCenter = CGPointMake(width/2, height/2);
    
    newCenter.y += self.arcRadius * sin(M_PI/180 * (angle - 90));
    newCenter.x += self.arcRadius * cos(M_PI/180 * (angle - 90));
    self.circle.center = newCenter;
    if (angle<180) {
        angle+=180;
    }
    else
    {
        angle-=180;
    }
    self.currentNum = (self.minNum + (self.maxNum - self.minNum)*(angle/360.0));
    
    NSLog(@"inside move circle current numb is %f", self.currentNum-2);
}


- (UIBezierPath *)createArcPathWithAngle:(double)angle atPoint: (CGPoint) point withRadius: (float) radius
{
    float endAngle = (float)(((int)angle + 270 + 1)%360);
    UIBezierPath *aPath = [UIBezierPath bezierPathWithArcCenter:point
                                                         radius:radius
                                                     startAngle:DEGREES_TO_RADIANS(122)
                                                       endAngle:DEGREES_TO_RADIANS(endAngle)
                                                      clockwise:YES];
    return aPath;
}

# pragma mark detect pan and determine angle of pan location vs. center of circular revolution

- (void) handlePan:(UIPanGestureRecognizer *)pv {
    
    CGPoint translation = [pv locationInView:self];
    CGFloat x_displace = translation.x - self.trueCenter.x;
    CGFloat y_displace = -1.0*(translation.y - self.trueCenter.y);
    double radius = pow(x_displace, 2) + pow(y_displace, 2);
    radius = pow(radius, .5);
    double angle = 180/M_PI*asin(x_displace/radius);
    
    
    if (x_displace > 0 && y_displace < 0){
        angle = 180 - angle;
    }
    else if (x_displace < 0){
        if(y_displace > 0){
            angle = 360.0 + angle;
        }
        else if(y_displace <= 0){
            angle = 180 + -1.0*angle;
        }
    }
    CGFloat tempAngle =angle;
    
    if (tempAngle<180) {
        tempAngle+=180;
    }
    else
    {
        tempAngle-=180;
    }
    CGFloat temp = (self.minNum + (self.maxNum - self.minNum)*(tempAngle/360.0))-3;
    if ( temp>=-1 && temp<=15) {
        [self moveCircleToAngle:angle];
    };
    
    
    
}


@end
